const https = require('https');
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const cheerio = require('../node_modules/cheerio')

let filePath = path.join(__dirname,"/index.html");
let options = url.parse('https://maoyan.com/films');
let movieList = [];
http.createServer((req,res) => {
    let urlObj = url.parse(req.url);
    if (urlObj.path == '/') {
        let readStream = fs.createReadStream(filePath);
        // console.log("1111")
        readStream.pipe(res);
    }
    else if (urlObj.path == "/getlist") {
        let rawData = '';
        https.get("https://maoyan.com/films",(ress) => {
            ress.on('data',chunk => {
                rawData+=chunk;
                // console.log(chunk.toString())
            })
            ress.on('end',() => {
                // console.log(rawData.toString())
                let $ = cheerio.load(rawData);
                $('.movie-item-title a').each((i,el) =>{
                    let movieName = $(el).text();
                    let movieId = $(el).attr('data-val');
                    movieId = movieId.slice(movieId.indexOf(":")+1,-1);
                    console.log(movieId)//获得电影id
                    let num1 = $(el).parent().next().children(".integer").text();
                    let num2 = $(el).parent().next().children(".fraction").text();
                    let score = `${num1}${num2}`;
                    score == ''?score = "暂无评分" : score;
                    let movieObj = {movieId:movieId,movieName:movieName,score:score};
                    movieList.push(movieObj);
                })
                console.log(movieList);
                res.writeHead(200,{"Content-Type":"text/plain"});
                res.write(JSON.stringify(movieList));
                res.end();
            })
        })
    }
}).listen(8081)
console.log("Server is listening 8081")